package com.nwcl.common.utils;

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.util.CollectionUtils;

import java.util.*;

/*
 * @Description:对象属性拷贝工具
 * @Author liguiqin
 * @Date 2023/5/26 10:55
 * @param: null
 * @return
 * @UpdateDate 2023/5/31 10:55
 **/
public class BeanUtil {
    //    创建过的BeanCopier实例放到缓存中，下次可以直接获取，提升性能
    static final Map<String, BeanCopier> BEAN_COPIERS = new HashMap<String, BeanCopier>();

    public static <T> T copy(Object srcObj, Class<T> beanClass) {
        if (srcObj == null) {
            return null;
        }
        T bean = null;
        try {
            bean = beanClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String key = genKey(srcObj.getClass(), bean.getClass());
        BeanCopier copier = null;
        if (!BEAN_COPIERS.containsKey(key)) {
            copier = BeanCopier.create(srcObj.getClass(), bean.getClass(), false);
            BEAN_COPIERS.put(key, copier);
        } else {
            copier = BEAN_COPIERS.get(key);
        }
        copier.copy(srcObj, bean, null);
        return bean;
    }

    public static <T, M> List<T> copyList(List<M> srcObjs, Class<T> beanClass) {
        if (CollectionUtils.isEmpty(srcObjs)) {
            return Collections.emptyList();
        }
        List<T> resultList = new ArrayList<>();
        try {
            for (M srcObj : srcObjs) {
                T bean = beanClass.newInstance();
                String key = genKey(srcObj.getClass(), bean.getClass());
                BeanCopier copier = null;
                if (!BEAN_COPIERS.containsKey(key)) {
                    copier = BeanCopier.create(srcObj.getClass(), bean.getClass(), false);
                    BEAN_COPIERS.put(key, copier);
                } else {
                    copier = BEAN_COPIERS.get(key);
                }
                copier.copy(srcObj, bean, null);
                resultList.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }

    private static String genKey(Class<?> srcClazz, Class<?> destClazz) {
        return srcClazz.getName() + destClazz.getName();
    }


}
